from app.models import BaseModel
from tools import db
from utils.enums import TextChoices


class ImageType(TextChoices):
    system = "0", "系统镜像"
    internal = "1", "内置镜像"
    user_upload = "2", "用户上传镜像"
    not_know = "3", ""


class ContainerFormat(TextChoices):
    bare = "bare"
    ovf = "ovf"
    aki = "aki"
    ari = "ari"
    ami = "ami"
    ova = "ova"
    docker = "docker"


class Image(db.Model, BaseModel):
    __tablename__ = "api_image"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    image_id = db.Column(db.String(120), unique=True, index=True, comment="镜像id")
    image_name = db.Column(db.String(120), comment="镜像名")
    image_full_name = db.Column(db.String(120), comment="镜像全名", default=None)
    image_type = db.Column(db.String(120), comment="镜像类型")
    image_explain = db.Column(db.String(250), comment="镜像说明", default=None)
    flavor_id = db.Column(db.String(120), comment="实例id")
    v4_fixed_ip = db.Column(db.BIGINT, default=None, comment="内网IP")
    # 0为系统镜像，用户不可见；1为内置镜像，用户可见不可编辑；2为用户上传镜像，用户可见可编辑
    status = db.Column(db.Enum("0", "1", "2", "3"), default="2", index=True)
    upload_path = db.Column(db.String(130))
    os_type = db.Column(db.Enum("windows", "linux"), default="linux", index=True)
    container_format = db.Column(
        db.Enum(*ContainerFormat.values), nullable=True, comment="容器格式"
    )
    tags = db.Column(db.JSON, nullable=True, comment="镜像标签")

    @staticmethod
    def get_flavor_id(image_id):
        for flavor_id in (
            Image.query.filter_by(image_id=image_id)
            .with_entities(Image.flavor_id)
            .first()
        ):
            return flavor_id

    def status_transition(self, status):
        status_dict = {"0": "system", "1": "built-in", "2": "upload"}
        return status_dict.get(status)

    def to_dict(self):
        return {
            "id": self.id,
            "image_id": self.image_id,
            "image_name": self.image_name,
            "image_type": self.image_type,
            "image_explain": self.image_explain,
            "status": self.status_transition(self.status),
            "upload_path": self.upload_path,
            "os_type": self.os_type,
            "image_full_name": self.image_full_name,
        }
